"""
User Management Serializers
"""
from rest_framework import serializers
from django.contrib.auth.models import User
from .models import UserGroup


class UserSimpleSerializer(serializers.ModelSerializer):
    """用户简单序列化器"""
    class Meta:
        model = User
        fields = ['id', 'username', 'email', 'first_name', 'last_name', 'is_active']


class UserGroupSerializer(serializers.ModelSerializer):
    """用户组序列化器"""
    user_count = serializers.IntegerField(read_only=True)
    category_display = serializers.CharField(source='get_category_display', read_only=True)
    users_detail = UserSimpleSerializer(source='users', many=True, read_only=True)
    user_ids = serializers.ListField(
        child=serializers.IntegerField(),
        write_only=True,
        required=False
    )
    
    class Meta:
        model = UserGroup
        fields = [
            'id', 'name', 'category', 'category_display', 'description',
            'users', 'users_detail', 'user_ids', 'user_count',
            'created_at', 'updated_at'
        ]
        read_only_fields = ['created_at', 'updated_at']
    
    def create(self, validated_data):
        user_ids = validated_data.pop('user_ids', [])
        user_group = UserGroup.objects.create(**validated_data)
        
        if user_ids:
            users = User.objects.filter(id__in=user_ids)
            user_group.users.set(users)
        
        return user_group
    
    def update(self, instance, validated_data):
        user_ids = validated_data.pop('user_ids', None)
        
        # 更新基本字段
        for attr, value in validated_data.items():
            setattr(instance, attr, value)
        instance.save()
        
        # 更新用户关系
        if user_ids is not None:
            users = User.objects.filter(id__in=user_ids)
            instance.users.set(users)
        
        return instance


class UserWithGroupsSerializer(serializers.ModelSerializer):
    """带组信息的用户序列化器"""
    groups = serializers.SerializerMethodField()
    
    class Meta:
        model = User
        fields = ['id', 'username', 'email', 'first_name', 'last_name', 
                  'is_active', 'is_staff', 'is_superuser', 'groups', 'date_joined']
    
    def get_groups(self, obj):
        """获取用户所属的组"""
        groups = obj.user_groups.all()
        return [{
            'id': g.id,
            'name': g.name,
            'category': g.category,
            'category_display': g.get_category_display()
        } for g in groups]
